package com.itheima.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;

    @Override
    public PageResult<Clazz> getPageResult(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> pageClazz = Page.of(page, pageSize);

        pageClazz = page(pageClazz);

        List<Clazz> clazzs = pageClazz.getRecords();

        List<Long> empId = clazzs.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());

        if(!empId.isEmpty()){
            List<Emp> emps = empService.listByIds(empId);

            clazzs.forEach(clazz -> {
                emps.forEach(emp -> {
                    if (clazz.getMasterId()!=null && clazz.getMasterId().equals(emp.getId())){
                        clazz.setMasterName(emp.getName());
                    }
                });
            });
        }

        for (Clazz clazz : clazzs) {
            if(LocalDate.now().isBefore(clazz.getBeginDate())){
                clazz.setStatus("未开班");
            } else if (LocalDate.now().isAfter(clazz.getEndDate())) {
                clazz.setStatus("已结课");
            } else {
                clazz.setStatus("已开班");
            }

        }
        return new PageResult<>(pageClazz.getTotal(),clazzs);
    }
}
